package one.stand;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jmp.base.MessageApi;
import com.jmp.base.dto.MessageWxSubscribeDto;
import com.jmp.feign.MessageFeign;
import com.jmp.im.ImNotifyClient;
import com.jmp.im.NotifyReceiveMsgRequest;
import lombok.extern.slf4j.Slf4j;
import one.stand.dto.UserDto;
import one.stand.enums.LoginEnum;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.MessageMsgService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import one.stand.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
public class ReceiveMsgActionServiceImpl implements ReceiveMsgActionService {
    @Autowired
    private MessageFeign messageFeign;
    @Autowired
    private ImNotifyClient imNotifyClient;

    @Autowired
    private MessageMsgService messageMsgService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @Override
    @Async("asyncServiceExecutor")
    public void execute(String requestBody, HttpServletRequest request) {
        NotifyReceiveMsgRequest receiveMsgRequest = JSON.parseObject(requestBody, NotifyReceiveMsgRequest.class);
        log.info("yunxin: {}", requestBody);
        if (imNotifyClient.check(request, requestBody) && receiveMsgRequest.getEventType() == 1) {
            messageMsgService.updateUnreadNum(receiveMsgRequest.getTo(), receiveMsgRequest.getFromAccount(), ImNotifyClient.TYPE);

            execute(receiveMsgRequest.getFromAccount(), receiveMsgRequest.getTo(), receiveMsgRequest.getBody());
        }
    }

    @Override
    @Async("asyncServiceExecutor")
    public void execute(String fromAccount, String toAccount, String content) {
        log.info("from {}, to {}: {}", fromAccount, toAccount, content);
        Integer fromId = Integer.valueOf(fromAccount);
        Integer toId = Integer.valueOf(toAccount);
//        if (tokenService.isLoginStatus(toId, LoginEnum.CRM)) {
//            return;
//        }

//        BusinessCard card = businessCardBaseService.getByUserId(toId);
//        if (Objects.nonNull(card)) {// push
//            User userModel = userAdminService.getByUserId(fromId);
//            String[] arr = {content};
//            MessagePushRequest pushRequest = MessagePushRequest.builder()
//                    .type(MessagePushType.UNREAD_MESSAGE)
//                    .fromId(fromId)
//                    .toId(toId)
//                    .fillData(arr)
//                    .title(userModel.getNickeName())
//                    .pageParams(new Object[]{fromId, userModel.getNickeName()})
//                    .build();
//            messageFeign.push(pushRequest);
//        } else {// wx

//        if (!tokenService.hasLoginStatus(toId, LoginEnum.CRM)) {
//        if (!tokenService.hasLoginStatus(toId, LoginEnum.CRM) && !tokenService.isLoginStatus(toId, LoginEnum.USER)) {
            UserDto userModel = userAdminService.get(fromId);
            String[] arr = {StrUtil.subSufByLength(userModel.getName(), 10), DateUtil.getDay(), content};
            MessageWxSubscribeDto messageDto = MessageWxSubscribeDto.builder()
                    .type(MessageApi.MSG_UNREAD)
                    .toId(toId)
                    .pageArr(new String[]{fromAccount})
                    .dataArr(arr)
                    .build();
            messageFeign.wxSubscribe(messageDto);
//        }
    }

    @Override
    @Async("asyncServiceExecutor")
    public void loginStatus(String to_account, boolean login, boolean app) {
        log.info("user {}: is Login(app[{}]):{}", to_account, app, login);
        Integer userId = Integer.valueOf(to_account);
        LoginEnum loginEnum = app ? LoginEnum.CRM : LoginEnum.USER;
        if (login) {
            tokenService.saveLoginStatus(userId, loginEnum.getCode());
        } else {
            tokenService.removeLoginStatus(userId, loginEnum);
        }
    }
}
